package br.com.bacabeleireiros.sysbeleza.service.impl;

import java.io.Serializable;
import java.util.HashMap;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import br.com.bacabeleireiros.sysbeleza.entity.Usuario;
import br.com.bacabeleireiros.sysbeleza.service.IRelatorioService;

@Service("relatorioService")
public class RelatorioServiceImpl implements IRelatorioService, Serializable {

	private static final long serialVersionUID = 1L;
	private String saida;
	
	@Autowired
	private DataSource ds;

	public RelatorioServiceImpl() {
		
	}
	
	@Override
	public String gerarRelatorio(HashMap<String, Object> parametros, String nomeRelatorio) {
		String jasper = null;
		String caminhoCabecalho = null;
		String caminhoSubRelatorio = null;
		try {
			
			caminhoCabecalho = getDiretorioReal("/pages/protected/relatorios/cabecalho.png");
			parametros.put("P_CABECALHO", caminhoCabecalho);
			parametros.put("P_USUARIO", this.getUsuarioSessao());
			caminhoSubRelatorio = getDiretorioReal("/pages/protected/relatorios/");
			parametros.put("SUBREPORT_DIR", caminhoSubRelatorio);
			
			jasper = getDiretorioReal("/pages/protected/relatorios/"+nomeRelatorio);
			
			JasperPrint print = JasperFillManager.fillReport(jasper, parametros, ds.getConnection());
			
			preenchePdf(print);
			
			return "/pages/protected/relatorio.xhtml";

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private void preenchePdf(JasperPrint print) throws JRException {
		saida = getDiretorioReal("/pages/protected/relatorios/relatorio.pdf");
		JasperExportManager.exportReportToPdfFile(print, saida);
		saida = getContextPath() + "/pages/protected/relatorios/relatorio.pdf";
	}
	
	private String getDiretorioReal(String diretorio) {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		return session.getServletContext().getRealPath(diretorio);
	}
	
	private String getContextPath() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		return session.getServletContext().getContextPath();
	}
	
	private String getUsuarioSessao() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		Usuario user = (Usuario) session.getAttribute("user");
		return user.getLogin();
	}

	public String getSaida() {
		return saida;
	}

	public void setSaida(String saida) {
		this.saida = saida;
	}

}